#include "Timer.h"
#include "stm32f10x.h"
#include "stm32f10x_tim.h"
#include "misc.h"
#include "CountSensor.h"
void init_timer(void){

    RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2,ENABLE);

    TIM_InternalClockConfig(TIM2);
    
    
    TIM_TimeBaseInitTypeDef time_base_def;
    TIM_TimeBaseStructInit(&time_base_def);
    time_base_def.TIM_ClockDivision = TIM_CKD_DIV1;
    time_base_def.TIM_CounterMode=TIM_CounterMode_Up;
    time_base_def.TIM_Period=10000;
    time_base_def.TIM_Prescaler = 7200;
    
    TIM_TimeBaseInit(TIM2,&time_base_def);
    
    
    TIM_ITConfig(TIM2,TIM_IT_Update,ENABLE);
    
    
    
    NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
    
    NVIC_Init(&(NVIC_InitTypeDef){
        .NVIC_IRQChannel=TIM2_IRQn,
        // 定时器的抢占优先级 要比 外部中断的优先级高
        // 否则定时器在计算频率时会读取 外部中断中累积的count变量
        // 会被 外部中断给打断，有可能造成变量的不一致（一个做累加操作，一个读取后做清零）
        .NVIC_IRQChannelPreemptionPriority=1,
        .NVIC_IRQChannelSubPriority=2,
        .NVIC_IRQChannelCmd=ENABLE
    });
    
    
    TIM_Cmd(TIM2,ENABLE);
    
}

uint16_t frequency;

void TIM2_IRQHandler(void){
    
    if(TIM_GetITStatus(TIM2,TIM_IT_Update)==SET){
    
        uint16_t count = getCountAndReset();
    
        frequency  = count /1;
    
        TIM_ClearITPendingBit(TIM2,TIM_IT_Update);
    }
  
    
}